#include <stdlib.h>

#include "lstack.h"

int lstack_init(lstack_t *lstack, size_t max_size)
{
    struct lstack_head head_init = {0, NULL};
    lstack->head = ATOMIC_VAR_INIT(head_init);
    lstack->size = ATOMIC_VAR_INIT(0);

    /* Pre-allocate all nodes. */
    lstack->node_buffer = malloc(max_size * sizeof(struct lstack_node));
    if (lstack->node_buffer == NULL)
        return ENOMEM;
    for (size_t i = 0; i < max_size - 1; i++)
        lstack->node_buffer[i].next = lstack->node_buffer + i + 1;
    lstack->node_buffer[max_size - 1].next = NULL;
    struct lstack_head free_init = {0, lstack->node_buffer};
    lstack->free = ATOMIC_VAR_INIT(free_init);
    return 0;
}


void lstack_for(lstack_t *lstack, void (*doItem)(void *value,void *param ),void *param)
{
	struct lstack_head next, orig = atomic_load(&lstack->head);
	do
	{
		if (orig.node == NULL)
            return ;
		if(doItem)
			(*doItem)(orig.node->value, param);
        next.aba = orig.aba + 1;
        next.node = orig.node->next;
		atomic_exchange(&orig , next);
	}while(1);
}